import { useEffect, useState, useRef } from 'react';
import { Link, useRequest, history } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { Button, Select, Breadcrumb, message, Spin, notification } from 'antd';
import { ToolOutlined } from '@ant-design/icons';
import moment from 'moment';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProCard,
  FooterToolbar,
  ProFormInstance,
} from '@ant-design/pro-components';

export default () => {
  const [gutter, setGutter] = useState(64);
  const [userId, setUserId] = useState();
  const [modalVisible, setModalVisible] = useState(false);
  const formRef = useRef<ProFormInstance>();
  const rules =
    localStorage.getItem('identity') === '管理员'
      ? []
      : [{ required: true, message: '请输入' }];
  //返回个人信息
  const getUserInfo = useRequest(
    (data = null) => {
      return {
        url: `http://10.1.40.84:9993/user/getUserInfo`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: (result, param) => {
        setUserId(result.id);
        formRef.current?.setFieldsValue({
          ...result.userGroupBo,
          talentLevelList: result.userGroupBo.talentLevelList || undefined,
          ...result,
        });
      },
    },
  );
  const getCountryType = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'countryType', ...data },
    };
  });
  const getCountry = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'country', ...data },
    };
  });
  const getGender = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'gender', ...data },
    };
  });
  const getIdType = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'idType', ...data },
    };
  });
  const getNation = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'nation', ...data },
    };
  });
  const getPoliticalStatus = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'politicalStatus', ...data },
    };
  });
  const getUnit = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'unit', ...data },
    };
  });
  const getTopEducationMajor = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'topEducationMajor', ...data },
    };
  });
  const getTechnicalGrade = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'technicalGrade', ...data },
    };
  });
  const getTechnicalName = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'technicalName', ...data },
    };
  });
  const getPosition = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'position', ...data },
    };
  });
  const getTopDegree = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'topDegree', ...data },
    };
  });
  const getTopEducation = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data: { field: 'topEducation', ...data },
    };
  });

  // //管理员返回id对应用户的信息，用于表单
  // const findOneUserInfoDetail = useRequest((data = null) => {
  //   return {
  //     url: 'http://10.1.40.84:9993/user/findOneUserInfoDetail',
  //     method: 'POST',
  //     headers: {
  //       Authorization: localStorage.getItem('token') || '',
  //     },
  //     data,
  //   };
  // });

  //返回方向下拉框
  const getDirectionLabel = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/direction/getDirectionLabel',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: () => {
        getUserInfo.run();
      },
    },
  );

  //返回团队下拉框
  const getGroupLabel = useRequest((data = '') => {
    return {
      url: `http://10.1.40.84:9993/group/getGroupLabel?level=${data}`,
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });

  //更新用户信息
  const updateUserById = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/user/updateUserById',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      formatResult: (res) => res,
    },
  );
  //fulfil
  useEffect(() => {
    console.log(localStorage.getItem('fulfil'));
    if (localStorage.getItem('fulfil') === '0') {
      notification['info']({
        placement: 'top',
        message: '基本信息不完善',
        description: '请完善个人的基本信息，提交成功后，重新登录系统！',
        style: { width: 500 },
        duration: null,
      });
    }
  }, []);
  return (
    <PageContainer
      header={{
        title: null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>个人中心</Breadcrumb.Item>
            <Breadcrumb.Item>基础信息</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
      extra={
        <ModalForm
          title={
            <>
              <ToolOutlined />
              <strong> {' 修改密码'}</strong>
            </>
          }
          trigger={
            <Button type="primary" icon={<ToolOutlined />}>
              修改密码
            </Button>
          }
          modalProps={{
            destroyOnClose: true,
          }}
          visible={modalVisible}
          onVisibleChange={setModalVisible}
          onFinish={async (values) => {
            if (values.confirmPassword != values.password) {
              message.error('确认密码与新密码不一致，请重新操作！');
            } else {
              updateUserById
                .run({
                  id: userId,
                  password: values.password,
                  oldPassword: values.oldPassword,
                })
                .then((res) => {
                  console.log(res);
                  if (res.code === 200) {
                    message.success('密码已更新，请重新登录');
                    history.push('/');
                    localStorage.clear();
                  } else if (res.code === 500) {
                    message.error(res.msg);
                  } else {
                    message.error('密码修改失败！');
                  }
                });
            }
            return true;
          }}
          layout={'horizontal'}
          width={600}
          grid
        >
          <ProFormText.Password
            name="oldPassword"
            label="旧密码"
            rules={[{ required: true, message: '请输入旧密码' }]}
          />
          <ProFormText.Password
            name="password"
            label="新密码"
            rules={[{ required: true, message: '请输入新密码' }]}
          />
          <ProFormText.Password
            name="confirmPassword"
            label="确认密码"
            rules={[{ required: true, message: '请输入确认密码' }]}
          />
        </ModalForm>
      }
    >
      <Spin spinning={!getUserInfo.data}>
        <ProCard
          gutter={[{ xs: 8, sm: 8, md: 16, lg: 24, xl: 8 }, 8]}
          style={{ marginBlockStart: 32 }}
        >
          <ProForm
            grid
            onFinish={async (values) => {
              console.log(values);
              updateUserById
                .run({
                  groupType: 0,
                  ...values,
                })
                .then((res) => {
                  if (res.code === 200) {
                    // getUserInfo.run()
                    message.success('修改成功');
                  } else {
                    message.error('修改失败');
                  }
                  if (localStorage.getItem('fulfil') === '0') {
                    localStorage.clear();
                    history.push('/');
                  }
                });
            }}
            submitter={{
              render: (_, dom) => (
                <FooterToolbar>
                  <Button type={'primary'} htmlType={'submit'}>
                    {' '}
                    提交
                  </Button>
                </FooterToolbar>
              ),
            }}
            formRef={formRef}
          >
            <ProFormText
              label="编号"
              name={'id'}
              colProps={{ span: 12 }}
              hidden
            />
            <ProForm.Group>
              <ProFormText
                label="工号"
                name={'username'}
                colProps={{ span: 4 }}
                rules={[{ required: true }]}
              />
              <ProFormText
                label="姓名"
                name={'realName'}
                colProps={{ span: 4 }}
                rules={[{ required: true }]}
              />
              <ProFormSelect
                label="用户状态"
                name={'status'}
                colProps={{ span: 4 }}
                options={[
                  { label: '正常', value: 1 },
                  { label: '停用', value: 0 },
                ]}
                disabled
              />
              <ProFormSelect
                mode={'multiple'}
                name={'roles'}
                label={'用户权限'}
                colProps={{ span: 4 }}
                options={[
                  { label: '管理员', value: 1 },
                  { label: '方向负责人', value: 2 },
                  { label: '子方向负责人', value: 3 },
                  { label: '成员', value: 4 },
                  { label: '学生', value: 5 },
                ]}
                disabled
              />
            </ProForm.Group>

            <ProCard title="研究信息" collapsible bordered headerBordered>
              <ProForm.Group>
                <ProFormSelect.SearchSelect
                  mode="single"
                  label="学院"
                  name={'unit'}
                  colProps={{ span: 4 }}
                  fieldProps={{
                    labelInValue: false,
                  }}
                  options={getUnit.data}
                  rules={[{ required: true, message: '请输入' }]}
                />
                <ProFormSelect
                  name={'technicalGrade'}
                  label={'技术职务等级'}
                  colProps={{ span: 4 }}
                  // required
                  options={getTechnicalGrade.data}
                  fieldProps={{
                    onChange: (e) => {
                      getTechnicalName.run({
                        field: 'technicalName',
                        level: e,
                      });
                      formRef.current?.setFieldsValue({ technicalName: '' });
                    },
                  }}
                  rules={rules}
                />
                <ProFormSelect
                  name={'technicalName'}
                  label={'技术职务名称'}
                  colProps={{ span: 4 }}
                  // required
                  options={getTechnicalName.data}
                  rules={rules}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormSelect
                  name={'directionId'}
                  label={'方向'}
                  options={getDirectionLabel.data}
                  fieldProps={{
                    onChange: (e) => {
                      getGroupLabel.run(e);
                    },
                  }}
                  colProps={{ span: 6 }}
                  disabled
                />
                <ProFormSelect
                  name={'groupId'}
                  label={'子方向'}
                  options={getGroupLabel.data}
                  colProps={{ span: 6 }}
                  disabled
                />
              </ProForm.Group>
              <ProForm.Group>
                {/* <ProFormSelect
                name={'jobNature'}
                label={'工作性质'}
                colProps={{ span: 6 }}
                required
                options={[
                  { label: '研究人员', value: '研究人员' },
                  { label: '技术人员', value: '技术人员' },
                  { label: '管理人员', value: '管理人员' },
                ]}
              /> */}
                {/* <ProFormSelect
                name={'position'}
                label={'实验室职务'}
                colProps={{ span: 6 }}
                required
                options={position}
              /> */}
              </ProForm.Group>
              <ProForm.Group>
                {/* <ProFormText
                name={'workUnit'}
                label={'工作单位'}
                colProps={{ span: 12 }}
              /> */}
                {/* <ProFormText
                name={'achievement'}
                label={'成果'}
                colProps={{ span: 6 }}
              />
              <ProFormText
                name={'honor'}
                label={'荣誉'}
                colProps={{ span: 6 }}
              />
              <ProFormText
                name={'topic'}
                label={'课题'}
                colProps={{ span: 6 }}
              /> */}
              </ProForm.Group>
            </ProCard>

            <ProCard
              title="学籍信息"
              collapsible
              defaultCollapsed
              bordered
              style={{ marginTop: 6 }}
              headerBordered
            >
              <ProForm.Group>
                <ProFormSelect
                  name={'isPostdoc'}
                  label={'是否博士后'}
                  colProps={{ span: 3 }}
                  options={[
                    { label: '是', value: '是' },
                    { label: '否', value: '否' },
                  ]}
                  rules={rules}
                />
                <ProFormSelect
                  name={'talentLevelList'}
                  label={'人才层次'}
                  colProps={{ span: 3 }}
                  options={[
                    { label: '院士', value: '院士' },
                    { label: '万人计划', value: '万人计划' },
                    { label: '长江学者', value: '长江学者' },
                    { label: '国家杰出青年', value: '国家杰出青年' },
                    { label: '其他国家级称号', value: '其他国家级称号' },
                    { label: '省级称号', value: '省级称号' },
                  ]}
                  fieldProps={{
                    mode: 'multiple',
                  }}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormSelect
                  name={'topEducation'}
                  label={'最高学历'}
                  colProps={{ span: 3 }}
                  options={getTopEducation.data}
                  rules={rules}
                />
                <ProFormSelect.SearchSelect
                  mode={'single'}
                  name={'topEducationMajor'}
                  label={'最高学历专业'}
                  colProps={{ span: 3 }}
                  fieldProps={{ labelInValue: false }}
                  options={getTopEducationMajor.data}
                  rules={rules}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormSelect
                  name={'topDegree'}
                  label={'最高学位'}
                  colProps={{ span: 3 }}
                  options={getTopDegree.data}
                  rules={rules}
                />
                <ProFormDatePicker.Month
                  name={'topDegreeGetTime'}
                  label={'学位授予时间'}
                  colProps={{ span: 3 }}
                  rules={rules}
                />
                <ProFormText
                  name={'topDegreeUnit'}
                  label={'学位授予单位'}
                  colProps={{ span: 3 }}
                  rules={rules}
                />
              </ProForm.Group>
            </ProCard>
            {/* <ProCard
              title="账号信息"
              collapsible
              defaultCollapsed
              bordered
              style={{ marginTop: 6 }}
              headerBordered
            >

            </ProCard> */}

            <ProCard
              title="户籍信息"
              collapsible
              defaultCollapsed
              bordered
              style={{ marginTop: 6 }}
              headerBordered
            >
              <ProForm.Group>
                <ProFormSelect
                  label="性别"
                  name={'gender'}
                  colProps={{ span: 3 }}
                  fieldProps={{
                    labelInValue: false,
                  }}
                  options={getGender.data}
                  rules={rules}
                />
                <ProFormDatePicker
                  label="生日"
                  name={'birthday'}
                  colProps={{ span: 3 }}
                  rules={rules}
                />
                <ProFormSelect
                  label="证件类型"
                  name={'idType'}
                  colProps={{ span: 3 }}
                  fieldProps={{
                    labelInValue: false,
                  }}
                  options={getIdType.data}
                  rules={rules}
                />
                <ProFormText
                  label="证件号码"
                  name={'idNumber'}
                  colProps={{ span: 3 }}
                  rules={rules}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormSelect
                  label="国别"
                  name={'countryType'}
                  colProps={{ span: 3 }}
                  // required
                  fieldProps={{
                    labelInValue: false,
                    onChange: (e) => {
                      getCountry.run({ field: 'country', level: e });
                      formRef.current?.setFieldsValue({ country: '' });
                    },
                  }}
                  options={getCountryType.data}
                  rules={rules}
                />
                <ProFormSelect.SearchSelect
                  mode="single"
                  label="国家"
                  name={'country'}
                  colProps={{ span: 3 }}
                  fieldProps={{
                    labelInValue: false,
                  }}
                  options={getCountry.data}
                  rules={rules}
                />
                <ProFormSelect.SearchSelect
                  mode="single"
                  label="民族"
                  name={'nation'}
                  colProps={{ span: 3 }}
                  fieldProps={{
                    labelInValue: false,
                  }}
                  options={getNation.data}
                  rules={rules}
                />
                <ProFormSelect.SearchSelect
                  mode="single"
                  label="政治面貌"
                  name={'politicalStatus'}
                  colProps={{ span: 3 }}
                  fieldProps={{
                    labelInValue: false,
                  }}
                  options={getPoliticalStatus.data}
                  rules={rules}
                />
              </ProForm.Group>
              <ProForm.Group rowProps={{ gutter: gutter }}></ProForm.Group>
            </ProCard>
            <ProCard
              title="联系方式"
              collapsible
              defaultCollapsed
              bordered
              style={{ marginTop: 6, marginBottom: 12 }}
              headerBordered
            >
              <ProForm.Group rowProps={{ gutter: gutter }}>
                <ProFormText
                  label="手机号码"
                  name={'mobilePhoneNum'}
                  colProps={{ span: 5 }}
                  rules={rules}
                />
                <ProFormText
                  label="电子邮箱"
                  name={'email'}
                  colProps={{ span: 5 }}
                  rules={rules}
                />
                <ProFormText
                  label="固定电话号码"
                  name={'phoneNum'}
                  colProps={{ span: 5 }}
                />
                <ProFormText
                  label="传真"
                  name={'faxNum'}
                  colProps={{ span: 5 }}
                />
              </ProForm.Group>
            </ProCard>
          </ProForm>
        </ProCard>
      </Spin>
    </PageContainer>
  );
};
